package com.xwj.xuthread.spring.nacos;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.xwj.xuthread.spring.core.ThreadPoolConfig;
import com.xwj.xuthread.spring.core.ThreadPoolManager;
import com.xwj.xuthread.spring.core.XuDynamicThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.yaml.snakeyaml.Yaml;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description TODO
 * @Author xwj
 * @Date 2025/8/24
 */
@Slf4j
public class NacosConfigListener implements ApplicationRunner {

    private ConfigService configService;

    @Autowired
    private ThreadPoolNacosConfig properties;

    @Autowired
    private ApplicationContext context;


    // 获取 extension-configs 中的 data-id
    @Value("${spring.cloud.nacos.config.extension-configs[0].data-id}")
    private String dataId;

    // 获取 extension-configs 中的 group
    @Value("${spring.cloud.nacos.config.extension-configs[0].group}")
    private String group;

    // 也可以获取 config 下的默认 group（如果需要）
    @Value("${spring.cloud.nacos.config.group:DEFAULT_GROUP}")
    private String defaultGroup;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        registerListener();
    }

    public NacosConfigListener(ConfigService configService) {
        this.configService = configService;
    }

    public void registerListener() throws NacosException {
        configService.addListener(
                dataId,
                group,
                new Listener() {
                    @Override
                    public Executor getExecutor() {
                        return null;
                    }

                    @Override
                    public void receiveConfigInfo(String configInfo) {
                        refreshThreadPoolProperties(configInfo);
                    }
                });

        log.info("Dynamic thread pool refresher, add nacos cloud listener success. data-id: {}, group: {}", dataId, group);
    }

    private void refreshThreadPoolProperties(String configInfo) {
        log.info("Dynamic thread pool refresher, receive nacos config info: {}", configInfo);
        // 解析配置信息
        ThreadPoolNacosConfig nacosConfig;
        try {
            nacosConfig = new Yaml().loadAs(configInfo, ThreadPoolNacosConfig.class);
        } catch (Exception e) {
            throw new RuntimeException("配置解析失败: " + e.getMessage(), e);
        }
        log.info("监听到的配置: {}", JSONUtil.parseArray( nacosConfig.getThreadPools()));
        List<ThreadPoolConfig> threadPools = nacosConfig.getThreadPools();
        ThreadPoolNacosConfig latestProperties = context.getBean(ThreadPoolNacosConfig.class);
        log.info("从自动刷新获得的配置: {}", JSONUtil.parseArray( latestProperties.getThreadPools()));
        log.info("从自动刷新获得的配置2: {}", JSONUtil.parseArray( properties.getThreadPools()));
        for(ThreadPoolConfig config : threadPools){
            log.info("线程池配置: {}", JSONUtil.parse(config));
            String threadPoolId = config.getThreadPoolId();
            XuDynamicThreadPool threadPool = ThreadPoolManager.getThreadPool(threadPoolId);
            if(threadPool == null){
                log.warn("线程池[{}]不存在，请在项目中定义", threadPoolId);
            } else {
                // 更新已有线程池配置
                ThreadPoolManager.updateThreadPoolConfig(config);
                log.info("更新已有线程池配置: {}", JSONUtil.parse(threadPool));
            }

        }
    }
}
